<script setup lang="ts">
import { type ButtonProps, message } from "ant-design-vue";
import { ref } from "vue";
import { showMessageAndPrint } from "@/framework/util/log.ts";
import { CmdTools } from "@/util/cmd-tools.ts";

const {
  serviceName,
  action = "start",
  loading,
  ...buttonProps
} = defineProps<
  {
    serviceName?: string;
    action?: "start" | "stop";
  } & ButtonProps
>();

const pending = ref(false);
const handleClick = async () => {
  if (!serviceName) return;
  try {
    pending.value = true;
    let success: boolean;
    if (action === "start") {
      success = await CmdTools.winsrv.start(serviceName);
    } else {
      success = await CmdTools.winsrv.stop(serviceName);
    }
    if (success) {
      message.success("操作成功");
    } else {
      message.error("操作失败");
    }
  } catch (e) {
    showMessageAndPrint(e);
  } finally {
    pending.value = false;
  }
};
</script>

<template>
  <a-button v-bind="buttonProps" :loading="loading || pending" @click="handleClick">
    <slot>{{ action === "start" ? "启动" : "停止" }}</slot>
  </a-button>
</template>

<style scoped lang="less"></style>
